/*    
 * 五星电器公司拥有完全的版权   
 * 使用者必须经过许可
 *----------------------------------------------------------------------*
 * Copyright  (c) 2016 FiveStar Co.,Ltd. All rights reserved
 * Author       : FiveStar Development
 * Description  : FsUserDetailsService.java
 *----------------------------------------------------------------------*
 * Change-History: Change history
 * Developer  Date      Description
 * shidong  2017年5月31日 Short description containing Message, Note ID or CR ID
 *----------------------------------------------------------------------*  
 */
package com.twp.auth.security;

import com.twp.auth.domain.authority.Role;
import com.twp.auth.domain.authority.user.ManageUser;
import com.twp.auth.service.manage.RoleService;
import com.twp.auth.service.user.ManageUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


/**
 * 此类功能描述
 *
 * @since JDK 1.8
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private ManageUserService managerUserService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String login) {

        String lowercaseLogin = login.toLowerCase();

            //用户名小于11位都是管理用户
            ManageUser userFromDatabase;

            userFromDatabase = managerUserService.findAllByUserName(lowercaseLogin);

            if (userFromDatabase == null) {
                throw new UsernameNotFoundException("ManagerUser " + lowercaseLogin + " was not found in the database");
            }

            //取用户角色列表
            List<Role> list = roleService.queryRolesByUid(userFromDatabase.getId());
            List<GrantedAuthority> authoritys = new ArrayList<GrantedAuthority>();
            for (Role role : list) {
                authoritys.add(new SimpleGrantedAuthority(role.getRoleName()));
            }

            return new org.springframework.security.core.userdetails.User(userFromDatabase.getUserName(),userFromDatabase.getPassword(), authoritys);

    }

}
